package cn.wolfcode.edu.util;

import cn.wolfcode.edu.domain.Employee;
import cn.wolfcode.edu.domain.SystemLog;
import cn.wolfcode.edu.mapper.SystemLogMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * Created by abb on 2018-07-07.
 */
public class SystemLogAspect {
    private SystemLogMapper systemLogMapper;

    public void setSystemLogMapper(SystemLogMapper systemLogMapper) {
        this.systemLogMapper = systemLogMapper;
    }
    public void writeLog(JoinPoint joinPoint) throws Exception {
        SystemLog log = new SystemLog();
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipal();
        if(employee != null){

            log.setOpUser(employee);
        }

        log.setOpTime(new Date());
        String functionName = joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName();
        log.setFunction(functionName);
        String args = new ObjectMapper().writeValueAsString(joinPoint.getArgs());
        log.setParams(args);
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        String ip = attributes.getRequest().getRemoteAddr();

        log.setOpIp(ip);
        systemLogMapper.insert(log);
    }
}
